package com.xcity.game.activity.thirtyday;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.xcity.db.entity.Player;
import com.xcity.game.activity.ActivityService;
import com.xcity.game.activity2.ActivityIds;
import com.xcity.game.common.Cause;
import com.xcity.game.common.MessageConst;
import com.xcity.game.common.PlayerPool;
import com.xcity.game.event.GameEvents;
import com.xcity.game.mail.MailAttach;
import com.xcity.game.mail.MailService;
import com.xcity.pomelo.PomeloRoute;
import com.xcity.pomelo.push.msg.ActivityStatePush;
import com.xcity.pomelo.request.ThirtyDayGetRewardRequest;
import com.xcity.pomelo.request.ThirtyDayRechargeGetRequest;
import com.xcity.pomelo.request.ThirtyDayRechargeSignListRequest;
import com.xcity.pomelo.request.ThirtyDayRewardListRequest;
import com.xcity.pomelo.request.ThirtyDayShopBuyRequest;
import com.xcity.pomelo.request.ThirtyDayShopListRequest;
import com.xcity.pomelo.response.HintResponse;
import com.xcity.pomelo.response.ThirtyDayGetRechargeRewardResponse;
import com.xcity.pomelo.response.ThirtyDayGetRewardResponse;
import com.xcity.pomelo.response.ThirtyDayRechargeListResponse;
import com.xcity.pomelo.response.ThirtyDayRechargeListResponse.RechargeRecordInfo;
import com.xcity.pomelo.response.ThirtyDayRewardListResponse;
import com.xcity.pomelo.response.ThirtyDayShopBuyResponse;
import com.xcity.pomelo.response.ThirtyDayShopListResponse;

import gnu.trove.map.hash.TIntObjectHashMap;
import naga.x.App;
import naga.x.event.Event;
import naga.x.event.EventListener;
import naga.x.game.template.TemplateService;
import naga.x.game.time.DayListener;
import naga.x.game.time.TimeUpdater;
import naga.x.net.Session;
import naga.x.net.annotation.OPHandler;
import naga.x.net.impl.pomelo.annotation.PomeloOP;
import naga.x.service.ServiceException;
import naga.x.util.TimeUtils;

/**
 * 30天签到(月签到)
 */
@OPHandler
public class ThirtyDaySignActivityService extends ActivityService implements EventListener, DayListener{

//	/**
//	 * 用于比较玩家签到时间 判断应该走本月模版还是下月模版
//	 */
//	private int startMoon = 0;//前一个月的时间 从0开始 
//	private int startYear = 0;//前一个月的时间
	
	private int thisMoon = -1;//从0开始
	private List<ThirtyDayRewardTemplate> curMoonList = new ArrayList<ThirtyDayRewardTemplate>(32);
//	private List<ThirtyDayRewardTemplate> nextMoonList = new ArrayList<ThirtyDayRewardTemplate>(32);
	
	private List<ThirtyDayRechargeTemplate> rechargeList = new ArrayList<ThirtyDayRechargeTemplate>(16);//价格从小到大
	private TIntObjectHashMap<ThirtyDayRechargeTemplate> id2RechargeTemp = new TIntObjectHashMap<ThirtyDayRechargeTemplate>();
	
	private TIntObjectHashMap<ThirtyDayShopTemplate> itemId2shopItem = new TIntObjectHashMap<ThirtyDayShopTemplate>();
	private List<ThirtyDayShopTemplate> shopItemList = new ArrayList<ThirtyDayShopTemplate>();
	
	public boolean isActive = true;//false;
	
	@Override
	public void startup() throws ServiceException {
		initCurMoonList();
//		initStartMoon();
		initTemplate();
		App.getApp().getEventManager().register(this);
		TimeUpdater.getInstance().addDayListener(this);
	}
	
	@Override
	public void shutdown() throws ServiceException {
	}

	@Override
	public int[] getEventTypes() {
		return new int[]{
				GameEvents.EVENT_PLAYER_LOADED,
				GameEvents.EVENT_PLAYER_LOGIN,
				GameEvents.EVENT_RECHARGE_OFFLINE,
				GameEvents.EVENT_RECHARGE,
		};
	}

	@Override
	public void handleEvent(Event event) {
		switch (event.getType()) {
		case GameEvents.EVENT_PLAYER_LOADED:
			playerLoaded(event.getParameter());
			break;
		case GameEvents.EVENT_PLAYER_LOGIN:
			playerLogin(event.getParameter());
			break;
		case GameEvents.EVENT_RECHARGE:
		case GameEvents.EVENT_RECHARGE_OFFLINE:
			handleRecharge(event.getParameter(0), event.getParameter(1));
			break;
		}
	}
	
	private void initCurMoonList(){
		int lastMoon = this.thisMoon;
		long now = TimeUpdater.getInstance().now();
		this.thisMoon = TimeUtils.getMoon(now);
		if(lastMoon != this.thisMoon){
			curMoonList.clear();
			List<ThirtyDayRewardTemplate> rewardList = App.getApp().getServiceManager().get(TemplateService.class).getTemplatesList(ThirtyDayRewardTemplate.class);
			for(int i = 0; i < rewardList.size(); i++){
				ThirtyDayRewardTemplate temp = rewardList.get(i);
				if(temp.getCurMoon() == this.thisMoon + 1){
					curMoonList.add(temp);
				}
			}
		}
	}

	@Deprecated
	private void initStartMoon(){
//		long now = TimeUpdater.getInstance().now();
//		this.startMoon = TimeUpdater.getMoon(now);
//		this.startYear = TimeUpdater.getYear(now);
//		int globalMoon = GameStaticConfig.activityThirty_Moon - 1;
//		int globalYear = GameStaticConfig.activityThirty_Year;
//		int curMoon, curYear;
//		if(globalMoon > 0){
//			curMoon = globalMoon - 1;
//			curYear = globalYear;
//		}else{
//			curMoon = 11;
//			curYear = globalYear - 1;
//		}
//		if(!(curMoon == this.startMoon && curYear == this.startYear)){
//			//配置已过期 则
//			this.startMoon = this.startMoon - 1;
//			if(this.startMoon < 0){
//				this.startMoon = 11;
//				this.startYear = this.startYear - 1;
//			}
//		}
	}
	
	private void initTemplate() throws ServiceException{
//		curMoonList.clear();
//		nextMoonList.clear();
//		List<ThirtyDayRewardTemplate> rewardList = App.getApp().getServiceManager().get(TemplateService.class).getTemplatesList(ThirtyDayRewardTemplate.class);
//		for(int i = 0; i < rewardList.size(); i++){
//			ThirtyDayRewardTemplate temp = rewardList.get(i);
//			if(temp.getCurMoon() == 0){
//				curMoonList.add(temp);
//			}else{
//				nextMoonList.add(temp);
//			}
//		}
		this.rechargeList.clear();
		this.id2RechargeTemp.clear();
		List<ThirtyDayRechargeTemplate> list = App.getApp().getServiceManager().get(TemplateService.class).getTemplatesList(ThirtyDayRechargeTemplate.class);
		if(ThirtyDayRechargeTemplate.RECHARGE_IDS_MAX != list.size()){
			throw new ServiceException("充值档位不符合规则");
		}
		for(int i = 0; i < list.size(); i++){
			ThirtyDayRechargeTemplate temp = list.get(i);
			temp.setId(i);
			id2RechargeTemp.put(i, temp);
			if(temp.getRechargeCount() > 3){
				temp.setRechargeCount(3);
			}
			rechargeList.add(temp);
		}
		Collections.sort(this.rechargeList);
		
		this.itemId2shopItem.clear();
		shopItemList.clear();
		List<ThirtyDayShopTemplate> shopList = App.getApp().getServiceManager().get(TemplateService.class).getTemplatesList(ThirtyDayShopTemplate.class);
		for(int i = shopList.size() - 1; i > -1; i--){
			ThirtyDayShopTemplate temp = shopList.get(i);
			if(temp.getCount() > 0){
				itemId2shopItem.put(temp.getId(), temp);
				shopItemList.add(temp);
			}
		}
		shopItemList.sort(new Comparator<ThirtyDayShopTemplate>() {
			@Override
			public int compare(ThirtyDayShopTemplate o1, ThirtyDayShopTemplate o2) {
				if(o1.getType() == o2.getType()){
					return o1.getId() - o2.getId();
				}
				return o1.getType() - o2.getType();
			}
		});
	}
	
	public void playerLoaded(Player player){
		//TODO 三十天签到
		if(isActive){
			player.send(new ActivityStatePush(ActivityIds.ACTIVITY_THIRTYDAY, STATE_OPENED));
		}
	}
	
	public void playerLogin(Player player){
		long now = TimeUpdater.getInstance().now();
		int curMoon = TimeUtils.getMoon(now);
		int curYear = TimeUtils.getYear(now);
		int lastSignDay = player.getPool().getInt(PlayerPool.PROPERTY_THIRTY_DAY_LAST_SIGN_DAY, 0);
		int totalDay = player.getPool().getInt(PlayerPool.PROPERTY_THIRTY_DAY_TOTAL_DAY, 0);
		if(lastSignDay > 0){
			Calendar cal = Calendar.getInstance();
			cal.set(Calendar.YEAR, lastSignDay >> 16);
			cal.set(Calendar.DAY_OF_YEAR, lastSignDay & 0xFFFF);
			long lastTime = cal.getTimeInMillis();//lastSignDay * 24 * 3600 * 1000L;
			int lastSignMoon = TimeUtils.getMoon(lastTime);
			int lastSignYear = TimeUtils.getYear(lastTime);
			if(curMoon != lastSignMoon || curYear != lastSignYear){
				totalDay = 0;
			}
		}else{
			totalDay = 0;
		}
		player.getPool().put(PlayerPool.PROPERTY_THIRTY_DAY_TOTAL_DAY, totalDay);
		LOG.info("[THIRTYDAY]ID[{}]TOTALDAY[{}]LASTDAY[{}]CAUSE[{}]", player.getId(), totalDay, lastSignDay, Cause.THIRTYDAY_LOGIN);
	}
	
	public void handleRecharge(Player player, int money){
		//判断时间
//		long time = TimeUpdater.getInstance().now();
		int today = TimeUpdater.getInstance().today();
		int lastDay = player.getPool().getInt(PlayerPool.PROPERTY_THIRTY_DAY_LAST_DAY, 0);
		int lastMonday = player.getPool().getInt(PlayerPool.PROPERTY_THIRTY_DAY_LAST_MONDAY, 0);
		boolean isThisWeek = true;
		boolean isToday = true;
		int thisMonday = TimeUtils.getMonday(today);//today - (getWeekDay(time) + 5) % 7;//0~6;
		if(thisMonday != lastMonday){
			isThisWeek = false;
			isToday = false;
		}else{
			if(lastDay != today){
				isToday = false;
			}
		}
		int record = player.getPool().getInt(PlayerPool.PROPERTY_THIRTY_DAY_RECHARGE_RECORD, 0);
		//判断档位
		int newRecord = 0;
		int matchId = -1;
		for(int i = rechargeList.size() - 1; i > -1; i--){
			ThirtyDayRechargeTemplate temp = rechargeList.get(i);
			int data = (record >> (temp.getId() * 4)) & 0xF;//0000
			if(temp.getRechargeMoney() > 0 && temp.getRechargeCount() > 0){
				//模版数据有效
				if(temp.getType() == 0){
					//日充值档位
					if(!isToday){
						data = 0;
					}
					int rechargeData = data & 0x3;//0011
					if(money >= temp.getRechargeMoney()){
						if(rechargeData < temp.getRechargeCount()){
							if(matchId == -1){
								rechargeData++;
								matchId = temp.getId();
							}
						}
					}
					int getData = data & 0xC;//1100
					data = getData | rechargeData;
				}else{
					//周充值档位
					if(!isThisWeek){
						data = 0;
					}
					int rechargeData = data & 0x3;//0011
					if(money >= temp.getRechargeMoney()){
						if(rechargeData < temp.getRechargeCount()){
							if(matchId == -1){
								rechargeData++;
								matchId = temp.getId();
							}
						}
					}
					int getData = data & 0xC;//1100
					data = getData | rechargeData;
				}
			}else{
				//被标记为无效模版数据 清除记录
				data = 0;
			}
			newRecord = newRecord | (data << (temp.getId() * 4));
		}
		player.getPool().put(PlayerPool.PROPERTY_THIRTY_DAY_RECHARGE_RECORD, newRecord);
		player.getPool().put(PlayerPool.PROPERTY_THIRTY_DAY_LAST_DAY, today);
		player.getPool().put(PlayerPool.PROPERTY_THIRTY_DAY_LAST_MONDAY, thisMonday);
		LOG.info("[THIRTYDAY]ID[{}]REWARDID[{}]OLDRECORD[{}]NEWRECORD[{}]", player.getId(), matchId, record, newRecord);
	}

	@PomeloOP(PomeloRoute.ACTIVITY_THIRTY_DAY_RECHARGE_LIST)
	public void requestRechargeRecordList(Session session, ThirtyDayRechargeSignListRequest req){
		Player player = session.getClient();
		int record = player.getPool().getInt(PlayerPool.PROPERTY_THIRTY_DAY_RECHARGE_RECORD, 0);
		//判断时间
//		long time = TimeUpdater.getInstance().now();
		int today = TimeUpdater.getInstance().today();
		int lastDay = player.getPool().getInt(PlayerPool.PROPERTY_THIRTY_DAY_LAST_DAY, 0);
		int lastMonday = player.getPool().getInt(PlayerPool.PROPERTY_THIRTY_DAY_LAST_MONDAY, 0);
		boolean isThisWeek = true;
		boolean isToday = true;
		int thisMonday = TimeUtils.getMonday(today);//today - (getWeekDay(time) + 5) % 7;//0~6;
		if(thisMonday != lastMonday){
			isThisWeek = false;
			isToday = false;
		}else{
			if(lastDay != today){
				isToday = false;
			}
		}
		//判断档位
//		int newRecord = 0;
		List<RechargeRecordInfo> retList = new ArrayList<RechargeRecordInfo>();
		for(int i = rechargeList.size() - 1; i > -1; i--){
			ThirtyDayRechargeTemplate temp = rechargeList.get(i);
			int data = (record >> (temp.getId() * 4)) & 0xF;//0000
			if(temp.getRechargeMoney() > 0 && temp.getRechargeCount() > 0){
				//模版数据有效
				if(temp.getType() == 0){
					//日充值档位
					if(!isToday){
						//过期
						data = 0;
					}
				}else{
					//周充值档位
					if(!isThisWeek){
						//过期
						data = 0;
					}
				}
				int rechargeData = data & 0x3;//0011
				int getData = (data & 0xC) >> 2;//1100
				RechargeRecordInfo info = new RechargeRecordInfo(temp, getData, rechargeData);
				retList.add(info);
			}else{
				//被标记为无效模版数据 清除记录
				data = 0;
			}
//			newRecord = newRecord | (data << (temp.getId() * 4));
		}
//		player.getPool().put(PlayerPool.PROPERTY_THIRTY_DAY_RECHARGE_RECORD, newRecord);
//		player.getPool().put(PlayerPool.PROPERTY_THIRTY_DAY_LAST_DAY, today);
//		player.getPool().put(PlayerPool.PROPERTY_THIRTY_DAY_LAST_MONDAY, thisMonday);
		player.send(new ThirtyDayRechargeListResponse(req.getSerial(), retList));
	}
	
	@PomeloOP(PomeloRoute.ACTIVITY_THIRTY_DAY_SHOP_LIST)
	public void requestShopList(Session session, ThirtyDayShopListRequest req){
		Player player = session.getClient();
		int today = TimeUpdater.getInstance().today();
//		Map<Integer, Integer> itemId2count = new HashMap<Integer, Integer>();
		TIntObjectHashMap<Integer> itemId2count = new TIntObjectHashMap<Integer>();
		int[] keys = itemId2shopItem.keys();
		int lastDay = player.getPool().getInt(PlayerPool.PROPERTY_THIRTY_DAY_SHOP_LAST_DAY, 0);
		if(lastDay == today){
			JSONObject map = player.getPool().getJSONObject(PlayerPool.PROPERTY_THIRTY_DAY_BOUGHT_DAY);
			if(map != null){
				for(int i = keys.length - 1; i > -1; i--){
					if(itemId2shopItem.get(keys[i]).getType() == 0){
						int count = map.getIntValue(String.valueOf(keys[i]));
						itemId2count.put(keys[i], count);
					}
				}
			}
		}
		int lastMonday = player.getPool().getInt(PlayerPool.PROPERTY_THIRTY_DAY_SHOP_LAST_MONDAY, 0);
		int thisMonday = TimeUtils.getMonday(today);//today - (getWeekDay(TimeUpdater.getInstance().now()) + 5) % 7;
		if(lastMonday == thisMonday){
			JSONObject map = player.getPool().getJSONObject(PlayerPool.PROPERTY_THIRTY_DAY_BOUGHT_MONDAY);
			if(map != null){
				for(int i = keys.length - 1; i > -1; i--){
					if(itemId2shopItem.get(keys[i]).getType() == 1){
						int count = map.getIntValue(String.valueOf(keys[i]));
						itemId2count.put(keys[i], count);
					}
				}
			}
		}
		player.send(new ThirtyDayShopListResponse(req.getSerial(), itemId2count, shopItemList));
	}

	@PomeloOP(PomeloRoute.ACTIVITY_THIRTY_DAY_SHOP_BUY)
	public void requestShopBuy(Session session, ThirtyDayShopBuyRequest req){
		Player player = session.getClient();
		int itemId = req.getItemId();
		ThirtyDayShopTemplate temp = itemId2shopItem.get(itemId);
		if(temp == null){
			player.send(new HintResponse(req.getSerial(), MessageConst.ACTIVITY_THIRTY_SHOPITEM_EMPTY));
			return;
		}
		//次数
		int count = 0;
		JSONObject map;
		int today = TimeUpdater.getInstance().today();
		if(temp.getType() == 0){
			int lastDay = player.getPool().getInt(PlayerPool.PROPERTY_THIRTY_DAY_SHOP_LAST_DAY, 0);
			map = player.getPool().getJSONObject(PlayerPool.PROPERTY_THIRTY_DAY_BOUGHT_DAY);
			if(today != lastDay || map == null){
				map = new JSONObject();
				player.poolSet(PlayerPool.PROPERTY_THIRTY_DAY_BOUGHT_DAY, map);
				player.getPool().put(PlayerPool.PROPERTY_THIRTY_DAY_SHOP_LAST_DAY, today);
			}
			count = map.getIntValue(String.valueOf(itemId));
			if(temp.getLimitCount() > 0){
				if(temp.getLimitCount() - count <= 0){
					player.send(new HintResponse(req.getSerial(), MessageConst.ACTIVITY_THIRTY_SHOPITEM_NO_COUNT));
					return;
				}
			}
		}else{
			int thisMonday = TimeUtils.getMonday(today);//today - (getWeekDay(TimeUpdater.getInstance().now()) + 5) % 7;
			int lastMonday = player.getPool().getInt(PlayerPool.PROPERTY_THIRTY_DAY_SHOP_LAST_MONDAY, 0);
			map = player.getPool().getJSONObject(PlayerPool.PROPERTY_THIRTY_DAY_BOUGHT_MONDAY);
			if(thisMonday != lastMonday || map == null){
				map = new JSONObject();
				player.poolSet(PlayerPool.PROPERTY_THIRTY_DAY_BOUGHT_DAY, map);
				player.getPool().put(PlayerPool.PROPERTY_THIRTY_DAY_SHOP_LAST_MONDAY, thisMonday);
			}
			count = map.getIntValue(String.valueOf(itemId));
			if(temp.getLimitCount() > 0){
				if(temp.getLimitCount() - count <= 0){
					player.send(new HintResponse(req.getSerial(), MessageConst.ACTIVITY_THIRTY_SHOPITEM_NO_COUNT));
					return;
				}
			}
		}
		//债券
		int costBond = temp.getCostBond();
		if(costBond > 0){
			if(player.getBond() < costBond){
				player.send(new HintResponse(req.getSerial(), MessageConst.ACTIVITY_THIRTY_SHOPITEM_NO_BOND));
				return;
			}
		}
		//钻石
		int costStone = temp.getCostStone();
		if(costStone > 0){
			if(!player.costStone(costStone, Cause.THIRTYDAY_BUY)){
				player.send(new HintResponse(req.getSerial(), MessageConst.ACTIVITY_THIRTY_SHOPITEM_NO_STONE));
				return;
			}
		}
		//加物品
		int itemCount = temp.getCount();
		player.getBag().addItemWithoutException(itemId, itemCount, Cause.THIRTYDAY_BUY);
		//扣债券
		if(costBond > 0){
			player.decBond(costBond, Cause.THIRTYDAY_BUY);
		}
		//扣次数
		count++;
		map.put(String.valueOf(itemId), count);
		if(temp.getType() == 0){
			player.poolSet(PlayerPool.PROPERTY_THIRTY_DAY_BOUGHT_DAY, map);
		}else{
			player.poolSet(PlayerPool.PROPERTY_THIRTY_DAY_BOUGHT_MONDAY, map);
		}
		int leftCount = temp.getLimitCount() - count;
		player.send(new ThirtyDayShopBuyResponse(req.getSerial(), itemId, leftCount));
	}

	@PomeloOP(PomeloRoute.ACTIVITY_THIRTY_DAY_RECHARGE_GET)
	public void requestRechargeGet(Session session, ThirtyDayRechargeGetRequest req){
		Player player = session.getClient();
		int record = player.getPool().getInt(PlayerPool.PROPERTY_THIRTY_DAY_RECHARGE_RECORD, 0);
//		long time = TimeUpdater.getInstance().now();
		int today = TimeUpdater.getInstance().today();
		int lastDay = player.getPool().getInt(PlayerPool.PROPERTY_THIRTY_DAY_LAST_DAY, 0);
		int lastMonday = player.getPool().getInt(PlayerPool.PROPERTY_THIRTY_DAY_LAST_MONDAY, 0);
		boolean isThisWeek = true;
		boolean isToday = true;
		int thisMonday = TimeUtils.getMonday(today);//today - (getWeekDay(time) + 5) % 7;//0~6;
		if(thisMonday != lastMonday){
			isThisWeek = false;
			isToday = false;
		}else{
			if(lastDay != today){
				isToday = false;
			}
		}
		ThirtyDayRechargeTemplate temp = id2RechargeTemp.get(req.getId());
		if(temp == null){
			player.send(new HintResponse(req.getSerial(), MessageConst.ACTIVITY_THIRTY_CANT_GET));
			return;
		}
		if(!(temp.getRechargeMoney() > 0 && temp.getRechargeCount() > 0)){
			player.send(new HintResponse(req.getSerial(), MessageConst.ACTIVITY_THIRTY_CANT_GET));
			return;
		}
		int data = (record >> (temp.getId() * 4)) & 0xF;
		if(!isToday && temp.getType() == 0){
			player.send(new HintResponse(req.getSerial(), MessageConst.ACTIVITY_THIRTY_GET_OVERTIME));
			return;
		}else if(!isThisWeek && temp.getType() == 1){
			player.send(new HintResponse(req.getSerial(), MessageConst.ACTIVITY_THIRTY_GET_OVERTIME));
			return;
		}
		int gotCount = (data & 0xC) >> 2;
		int rechargeCount = (data & 0x3);
		int canGet = rechargeCount - gotCount;
		if(canGet <= 0){
			player.send(new HintResponse(req.getSerial(), MessageConst.ACTIVITY_THIRTY_CANT_GET));
			return;
		}
		//领取次数 = 充值次数
		gotCount = rechargeCount;
		if(gotCount > ThirtyDayRechargeTemplate.RECHARGE_COUNT_MAX){
			gotCount = ThirtyDayRechargeTemplate.RECHARGE_COUNT_MAX;
		}
		int newData = (gotCount << 2) | rechargeCount;
		int newRecord = (record & (ThirtyDayRechargeTemplate.RECHARGE_RECORD_FULL ^ (0xF << (temp.getId() * 4)))) | (newData << (temp.getId() * 4));
		player.getPool().put(PlayerPool.PROPERTY_THIRTY_DAY_RECHARGE_RECORD, newRecord);
		//发奖励
		if(temp.getMoney() > 0){
			player.addGold(temp.getMoney() * canGet, Cause.THIRTYDAY_RECHARGE_GET);
		}
		if(temp.getBond() > 0){
			player.addBond(temp.getBond() * canGet, Cause.THIRTYDAY_RECHARGE_GET);
		}
		for(int i = 0; i < temp.getItemIds().length; i++){
			if(temp.getItemIds()[i] > 0 && temp.getItemCounts()[i] > 0){
				player.getBag().addItemWithoutException(temp.getItemIds()[i], temp.getItemCounts()[i] * canGet, Cause.THIRTYDAY_RECHARGE_GET);
			}
		}
		LOG.info("[THIRTYDAY]ID[{}]REWARDID[{}]OLDRECORD[{}]NEWRECORD[{}]GETCOUNT[{}]", player.getId(), req.getId(), record, newRecord, canGet);
		player.send(new ThirtyDayGetRechargeRewardResponse(req.getSerial(), req.getId()));
	}
	
	@PomeloOP(PomeloRoute.ACTIVITY_THIRTY_DAY_REWARD_LIST)
	public void requestRewardList(Session session, ThirtyDayRewardListRequest req){
		Player player = session.getClient();
		if(!isActive){
			player.send(new HintResponse(req.getSerial(), MessageConst.ACTIVITY_THIRTY_NOT_OPEN));
			return;
		}
		int lastDay = player.getPool().getInt(PlayerPool.PROPERTY_THIRTY_DAY_LAST_SIGN_DAY, 0);
		int today = TimeUpdater.getInstance().today();
		int totalDay = player.getPool().getInt(PlayerPool.PROPERTY_THIRTY_DAY_TOTAL_DAY, 0);
		int got = 1;
		if(lastDay < today){
			got = 0;
		}
		List<ThirtyDayRewardTemplate> list = getCurrentList();
		player.send(new ThirtyDayRewardListResponse(req.getSerial(), totalDay, list, got));
	}
	
	@PomeloOP(PomeloRoute.ACTIVITY_THIRTY_DAY_GET_REWARD)
	public void requestGetReward(Session session, ThirtyDayGetRewardRequest req){
		Player player = session.getClient();
		if(!isActive){
			player.send(new HintResponse(req.getSerial(), MessageConst.ACTIVITY_THIRTY_NOT_OPEN));
			return;
		}
		int today = TimeUpdater.getInstance().today();
		int lastDay = player.getPool().getInt(PlayerPool.PROPERTY_THIRTY_DAY_LAST_SIGN_DAY, 0);
		if(lastDay >= today){
			player.send(new HintResponse(req.getSerial(), MessageConst.ACTIVITY_THIRTY_DAY_ALREADY_GET));
			return;
		}
		int totalDay = player.getPool().getInt(PlayerPool.PROPERTY_THIRTY_DAY_TOTAL_DAY, 0);
		List<ThirtyDayRewardTemplate> list = getCurrentList();
		if(totalDay >= list.size()){
			player.send(new HintResponse(req.getSerial(), MessageConst.ACTIVITY_THIRTY_GET_ERROR));
			return;
		}
		ThirtyDayRewardTemplate temp = list.get(totalDay);
		int vipRate = 1;
		if(temp.getVip() > 0 && player.getVipLvl() >= temp.getVip()){
			//VIP双倍奖励
			vipRate = 2;
		}
		
		//发奖励
		MailAttach attach = new MailAttach(temp.getMoney() * vipRate, temp.getStone() * vipRate);
		String title = "月签到奖励";
		String content = "恭喜您获得月签到奖励";
		if(temp.getItems() > 0){
			attach.addItem(temp.getItems(), temp.getCount() * vipRate);
		}
		App.getApp().getServiceManager().get(MailService.class).sendSystemMail(player.getId(), title, content, attach);
		totalDay++;
		player.getPool().put(PlayerPool.PROPERTY_THIRTY_DAY_TOTAL_DAY, totalDay);
		player.getPool().put(PlayerPool.PROPERTY_THIRTY_DAY_LAST_SIGN_DAY, today);

		App.getApp().getEventManager().addEvent(GameEvents.EVENT_DAILY_SIGN, player);
		LOG.info("[THIRTYDAY]ID[{}]TOTALDAY[{}]LASTDAY[{}]CAUSE[{}]", player.getId(), totalDay, today, Cause.THIRTYDAY_GET);
		player.send(new ThirtyDayGetRewardResponse(req.getSerial(), totalDay - 1, 0));
	}
	
	protected List<ThirtyDayRewardTemplate> getCurrentList(){
		long now = TimeUpdater.getInstance().now();
//		int curMoon = TimeUpdater.getMoon(now);
//		int curYear = TimeUpdater.getYear(now);
		int curMoonMaxDay = TimeUtils.getMoonMaxDay(now);
		List<ThirtyDayRewardTemplate> list = new ArrayList<ThirtyDayRewardTemplate>(32);
//		if(this.startMoon == curMoon && this.startYear == curYear){
//			if(curMoonList.size() < curMoonMaxDay){
//				curMoonMaxDay = curMoonList.size();
//			}
//			for(int i = 0; i < curMoonMaxDay; i++){
//				list.add(curMoonList.get(i));
//			}
//		}else{
//			if(nextMoonList.size() < curMoonMaxDay){
//				curMoonMaxDay = nextMoonList.size();
//			}
//			for(int i = 0; i < curMoonMaxDay; i++){
//				list.add(nextMoonList.get(i));
//			}
//		}
		if(curMoonList.size() < curMoonMaxDay){
			curMoonMaxDay = curMoonList.size();
		}
		for(int i = 0; i < curMoonMaxDay; i++){
			list.add(curMoonList.get(i));
		}
		return list;
	}
	
	public static boolean isFirstLoginToday(Player player) {
		int lastRewardDay = player.getPool().getIntValue(PlayerPool.PROPERTY_THIRTY_DAY_LAST_SIGN_DAY);
		return lastRewardDay < TimeUpdater.getInstance().today();
	}
	
	@Deprecated
	//弃用 改用timeupdate的getMonday得到周一day 
	//返回周日到周一 1~7 
	public static int getWeekDay(long time){
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(time);
		return cal.get(Calendar.DAY_OF_WEEK);
	}
	
	@Deprecated
	public void setActive(boolean open){
		this.isActive = open;
	}

	@Override
	public boolean dayChanged() {
		initCurMoonList();
		return true;
	}
}
